import jwt
from rest_framework.authentication import BaseAuthentication
from utils.tooljwt import tooljwt
from rest_framework.response import Response
from user import models
import datetime
from rest_framework.exceptions import AuthenticationFailed


class JWTAuthenticationss(BaseAuthentication):
    def authenticate(self, request):
        # 获取token
        tokendata = request.META.get('HTTP_AUTHORIZATION', None)
        if tokendata:
            token = tokendata.split(' ')[1]
            # 验证token
            try:
                userdata = tooljwt.checktoken(token)
                user = models.UserModel.objects.get(id=userdata['userid'])
                expiretime = userdata['exp']
                return user, token
            except jwt.ExpiredSignatureError:
                raise AuthenticationFailed('Token已过期')
            except jwt.InvalidTokenError:
                raise AuthenticationFailed('无效的Token')
        else:
            return None, None
    def authenticate_header(self, request):
        return 'Bearer realm="api"'
